//
//  RWPayViewController.m
//  RedWine
//
//  Created by Liufangfang on 2016/12/27.
//  Copyright © 2016年 HuiBangKe. All rights reserved.
//

#import "RWPayViewController.h"

#import <AlipaySDK/AlipaySDK.h>
#import "RSADataSigner.h"
#import "Order.h"

#import "WXApi.h"

#define kPayButtonBaseTag 450

typedef NS_ENUM(NSInteger, RWPayStyle) {

    RWPayStyleApliPay = 0,
    RWPayStyleWeChat
};

@interface RWPayViewController (){

    NSArray *sectionHeaderTitles;
    NSArray *paySums;
    NSArray *payCoupons;
    CGFloat _recharge;
}

@property (nonatomic, strong) UIButton *amountBGV;
@property (nonatomic, strong) UIButton *apliPayBtn;
@property (nonatomic, strong) UIButton *weChatBtn;

@property (nonatomic, assign) RWPayStyle payStyle;

@end

@implementation RWPayViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initObjects];
    [self setNavigation];
    [self setPayUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess:) name:@"ALiPay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess:) name:@"WXPay" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Load Datas

- (void)initObjects{

    sectionHeaderTitles = @[@"请选择充值金额：", @"充值方式："];
    paySums = @[@"5000元", @"10000元", @"20000元", @"50000元"];
    payCoupons = @[@"充值即赠200元", @"充值即赠500元", @"充值即赠1200元", @"充值即赠4000元"];
}

- (void)loadDatas{
    
    
}

#pragma mark - Config UI

- (void)setNavigation{
    
    self.title = @"充值中心";
}

- (void)setPayUI{
    
    _payTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT- FTY_TABBAR_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:_payTV];
    _payTV.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
    _payTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _payTV.dataSource = self;
    _payTV.delegate = self;
    _payTV.scrollEnabled = NO;
    [self addBottomBtn];
}

#pragma mark - Config Invoke Methods

- (void)addBottomBtn{

    UIButton *payBtn = [[UIButton alloc] init];
    [self.view addSubview:payBtn];
    payBtn.backgroundColor = [FTYColor getMainColorWithAlpha:1.];
    payBtn.layer.masksToBounds = YES;
    payBtn.layer.cornerRadius = 5.*FTY_WIDTH_BASE;
    [payBtn setTitle:@"去充值" forState:UIControlStateNormal];
    [payBtn addTarget:self action:@selector(payBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(10.*FTY_WIDTH_BASE);
        make.bottom.mas_offset(-150.*FTY_HEIGHT_BASE);
        make.right.mas_offset(-10.*FTY_HEIGHT_BASE);
        make.height.mas_offset(40.*FTY_HEIGHT_BASE);
    }];
}

#pragma mark - Notificaiton Method

#pragma mark - Notificaiton Invoke Methods

#pragma mark - <UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (1 == section) {
        return 2;
    } else{
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 50.*FTY_HEIGHT_BASE;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if ( 0 == indexPath.section) {
        return 150.*FTY_HEIGHT_BASE;
    } else {
        return 50.*FTY_HEIGHT_BASE;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, 50.*FTY_HEIGHT_BASE)];
    headerV.backgroundColor = [UIColor clearColor];
    
    UILabel *titleLab = [[UILabel alloc] init];
    [headerV addSubview:titleLab];
    titleLab.text = sectionHeaderTitles[section];
    titleLab.textColor = [FTYColor blackColor];
    titleLab.font = FTY_FONTTSIZE(15);
    [titleLab sizeToFit];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_offset(0);
        make.left.mas_offset(10*FTY_WIDTH_BASE);
        make.right.mas_offset(-10*FTY_WIDTH_BASE);
    }];
    
    return headerV;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString * const payID = @"payID";
    UITableViewCell *payCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:payID];
    payCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    NSArray *section1Images = @[@"alipay_icon", @"weixin_icon"];
    NSArray *section1Titles = @[@"支付宝支付", @"微信支付"];
    
    if (0 == section) {//充值金额section
        
        payCell.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
        
        for (int i=0; i<4; i++) {
            
            CGFloat bgTop = 0;
            CGFloat bgLeft = 25.*FTY_WIDTH_BASE;
            if (1 == i ) {
                bgLeft = 200.*FTY_WIDTH_BASE;
            } else if(2 == i){
                bgTop = 94.*FTY_HEIGHT_BASE;
            } else if(3 == i){
                bgTop = 94.*FTY_HEIGHT_BASE;
                bgLeft = 200.*FTY_WIDTH_BASE;
            }
            
            UIButton *amountBGV = [[UIButton alloc] init];
            [payCell addSubview:amountBGV];
            amountBGV.backgroundColor = [UIColor whiteColor];
            amountBGV.tag = 300+i;
            [amountBGV addTarget:self action:@selector(amountBGBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            [amountBGV mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(bgTop);
                make.left.mas_equalTo(bgLeft);
                make.width.mas_equalTo(137.*FTY_WIDTH_BASE);
                make.height.mas_equalTo(63.*FTY_HEIGHT_BASE);
            }];
            _amountBGV = amountBGV;
            
            //总面额
            UILabel *sumLab = [[UILabel alloc] init];
            [_amountBGV addSubview:sumLab];
            sumLab.text = paySums[i];
            sumLab.textColor = [FTYColor getMainColorWithAlpha:1.];
            sumLab.font = FTY_FONTTSIZE(18);
            [sumLab sizeToFit];
            [sumLab mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(10.*FTY_HEIGHT_BASE);
                make.centerX.mas_equalTo(_amountBGV.mas_centerX);
            }];
            
            //充值优惠
            UILabel *couponLab = [[UILabel alloc] init];
            [_amountBGV addSubview:couponLab];
            couponLab.text = payCoupons[i];
            couponLab.textColor = [FTYColor blackColor];
            couponLab.font = FTY_FONTTSIZE(13);
            [couponLab sizeToFit];
            [couponLab mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(sumLab.mas_bottom).offset(6.*FTY_HEIGHT_BASE);
                make.centerX.mas_equalTo(_amountBGV.mas_centerX);
            }];
        }
    } else {//支付方式section
    
        payCell.imageView.image = [UIImage imageNamed:section1Images[row]];
        payCell.textLabel.text = section1Titles[row];
        payCell.textLabel.font = FTY_FONTTSIZE(15);
        
        UIButton *selectBtn = [[UIButton alloc] init];
        [payCell.contentView addSubview:selectBtn];
        [selectBtn setImage:[UIImage imageNamed:@"noselected_icon"] forState:UIControlStateNormal];
        [selectBtn setImage:[UIImage imageNamed:@"selected_icon"] forState:UIControlStateSelected];
        selectBtn.tag = kPayButtonBaseTag + row;
        [selectBtn addTarget:self action:@selector(selectBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(payCell.mas_centerY);
            make.right.mas_equalTo(-10.*FTY_WIDTH_BASE);
            make.width.height.mas_equalTo(30.*FTY_WIDTH_BASE);
        }];
        
        if (0 == indexPath.row) {
            selectBtn.selected = YES;
            _apliPayBtn = selectBtn;
        } else {
            _weChatBtn = selectBtn;
        }
        
        if (0 == row) {
            
            UIView *line = [[UIView alloc] init];
            [payCell addSubview:line];
            line.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
            [line mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.bottom.right.mas_offset(0);
                make.height.mas_offset(.5*FTY_HEIGHT_BASE);
            }];
        }
    }
    
    return payCell;
}

#pragma mark - <UITableViewDelegate>

#pragma mark - Private Invoke Methods

- (void)amountBGBtnAction:(UIButton *)btn{
    
    //选中一个按钮 其他都为非选择状态
    UIView *view = btn.superview;
    for (UIView *otherBtn in view.subviews) {
        
        otherBtn.layer.masksToBounds = NO;
        otherBtn.layer.borderColor = nil;
        otherBtn.layer.borderWidth = 0;
    }
    btn.layer.masksToBounds = YES;
    btn.layer.borderColor = [FTYColor getMainColorWithAlpha:1.].CGColor;
    btn.layer.borderWidth = 1.*FTY_WIDTH_BASE;

    
    switch (btn.tag) {
        case 300:
            _recharge = 5000;
            break;
        case 301:
            _recharge = 10000;
            break;
        case 302:
            _recharge = 20000;
            break;
        case 303:
            _recharge = 50000;
            break;
            
        default:
            break;
    }
    
    
}

- (void)selectBtnAction:(UIButton *)btn{

    btn.selected = !btn.selected;
    if (450 == btn.tag) {
        _payStyle = RWPayStyleApliPay;
        _weChatBtn.selected = NO;
    } else if(451 == btn.tag) {
        _payStyle = RWPayStyleWeChat;
        _apliPayBtn.selected = NO;
    }
}

- (void)payBtnAction:(UIButton *)btn{
    
    switch (_payStyle) {
            
        case RWPayStyleApliPay:
            [self gotoApliPay];
            break;
            
        case RWPayStyleWeChat:
            
            if ([WXApi isWXAppInstalled]) {
                [self gotoWeChatPay];
            } else { //未安装微信
                UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:nil message:@"您未安装微信客户端～" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"好的", nil];
                [alertview show];
                return;
            }
            break;
            
        default:
            break;
    }
}

#pragma mark - ApliPay Methods

//支付宝支付
- (void)gotoApliPay{

    FTYUser *user = [FTYUser sharedUser];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/ali.php?method=alipay&member_id=%@&token=%@&recharge=%@", user.userID, user.userToken, [NSNumber numberWithFloat:_recharge]] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            NSInteger codeInfo = [[[result objectForKey:@"err"] objectForKey:@"errorcode"] integerValue];
            NSString *info = [[result objectForKey:@"err"] objectForKey:@"errorinfo"];
            NSDictionary *userInfo = result[@"info"];
            if (0 == codeInfo) {
                [self aliPay:userInfo];
            } else {
                [[FTYToastView alloc] addTitle:info addView:self.view];
            }
        } else {
        
        }
    }];
}

- (void)aliPay:(NSDictionary *)dic{
    // NOTE: 调用支付结果开始支付
    
    NSString *orderString = [dic objectForKey:@"url"];
    NSString *appScheme = @"alipayHBKRedWine";
    
    
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
    }];
}

- (void)paySuccess:(NSNotification *)notify
{
    [self.navigationController popToRootViewControllerAnimated:NO];
}

#pragma mark - WeChatPay Methods

//微信支付
- (void)gotoWeChatPay{

    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=topay&method=%@&member_id=%@&token=%@&recharge=%@", @"wx", [FTYUser sharedUser].userID, [FTYUser sharedUser].userToken, [NSNumber numberWithFloat:_recharge]] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            NSInteger codeInfo = [[[result objectForKey:@"err"] objectForKey:@"errorcode"] integerValue];
            NSString *info = [[result objectForKey:@"err"] objectForKey:@"errorinfo"];
            NSDictionary *userInfo = result[@"info"];
            if (0 == codeInfo) {
                [self weChat:userInfo];
            } else {
                [[FTYToastView alloc] addTitle:info addView:self.view];
            }
        } else {
        
        }
    }];
}

- (void)weChat:(NSDictionary *)dic{

//    NSLog(@"====%@", dic);
    //调起微信支付
    PayReq* req             = [[PayReq alloc] init];
    req.partnerId           = [dic objectForKey:@"partnerid"];
    req.prepayId            = [dic objectForKey:@"prepayid"];
    req.nonceStr            = [dic objectForKey:@"noncestr"];
    req.timeStamp           = [[dic objectForKey:@"timestamp"] intValue];
    req.package             = [dic objectForKey:@"packageX"];
    req.sign                = [dic objectForKey:@"sign"];
    [WXApi sendReq:req];
}


@end
